package com.wxtf.platform.main.contraceptives;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.plugins.user.UserBean;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.ConstantInfoHelper;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.FormatUtil;

/**
 * <li>Title: ContraceptiveAction.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.main.contraceptives</li>
 * <li>Description: 药具字典</li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li>Created on Aug 21, 2012 10:29:02 AM</li>
 * 
 * @author zhanqiulin
 * @version 1.0.0.0
 * 
 */
public class ContraceptiveManagerAction extends LogicBase implements CommonsCallProvider{
	private static final Log log = LogFactory.getLog(ContraceptiveManagerAction.class);

	public ContraceptiveManagerAction(String jsonArray){

	}
	
	@Override
	public Object run() {
		Object msg = "";
		try {
			if("queryPage".equals(this.getMethodName())) {
				msg = this.select(this.getLogicData());
				return msg;
			} else if("save".equals(this.getMethodName())) {
				msg = this.insert(this.getLogicData());
			} else if("update".equals(this.getMethodName())) {
				msg = this.update(this.getLogicData());
			} else if("delete".equals(this.getMethodName())) {
				msg = this.delete(this.getLogicData());
			} else if("getConTitle".equals(this.getMethodName())) {
				msg = this.getConTitle(this.getLogicData());
				return msg;
			} else {
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}

			if(msg == null || "[null]".equals(msg)) {
				msg = "\"\"";
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString());
		} catch(Exception e) {
			msg = ConstantInfoHelper.generateErrorJSONString();
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}

	String[] fields = {"tmad_id","tmad_kind","tmad_name","tmad_description","tmad_spec","tmad_unit","tmad_company_name","tmad_formulation","tmad_batch_code","tmad_qgp","tmad_status","tmad_install","tmad_price","tmad_memo",
			"reserve1","reserve2","reserve3","reserve4","reserve5","create_by","create_time","last_modify_by","last_modify_time"
	};
	@Override
	public Object select(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		sql = "from tma_dictionary ";
		if(array.size() > 0) {
			JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
			String types = jsonObject.getString("types");
			if("init".equals(types)) {// 初始查询
				
			} else if("serch1".equals(types)) {// 条件查询
				String name_query = jsonObject.getString("name_query");//药具名称
				String type_query = jsonObject.getString("type_query");//药具类型
				String status_query = jsonObject.getString("status_query");//药具状态
				String reserve1_query = jsonObject.getString("reserve1_query");//是否用于发放
				StringBuffer buff = new StringBuffer();
				buff.append(" where 1=1 ");
				if(StringUtils.isNotBlank(type_query)){
					buff.append(" and tmad_kind = '").append(type_query).append("'");
				}
				if(StringUtils.isNotBlank(name_query)){
					buff.append(" and tmad_name like '%").append(name_query).append("%'");
				}
				if(StringUtils.isNotBlank(status_query)){
					buff.append(" and tmad_status = '").append(status_query).append("'");
				}
				if(StringUtils.isNotBlank(reserve1_query)){
					if("1".equals(reserve1_query)){
						buff.append(" and reserve1 = '1'");
					}else{
						buff.append(" and reserve1 <> '1'");
					}
				}
				sql += buff.toString();
			} 
		}
		Object[] params = null;
		String countSql = "select count(*) " + sql;
		String querySql = "select tmad_id,tmad_kind,tmad_name,tmad_description,tmad_spec,tmad_unit,tmad_company_name,tmad_formulation,tmad_batch_code,tmad_qgp,tmad_status,tmad_install,tmad_price,tmad_memo,reserve1,reserve2,reserve3,reserve4,reserve5,create_by,create_time,last_modify_by,last_modify_time " 
			+ sql+" order by tmad_kind desc,tmad_name";
		
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), params);
	}

	@Override
	public Object insert(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		
		StringBuffer buff = new StringBuffer();
		buff.append("insert into tma_dictionary(tmad_id");
		Object[] obj = new Object[fields.length];
		for (int j = 1; j < fields.length; j++) {
			obj[j] = jsonObject.getString(fields[j]);
			buff.append(",").append(fields[j]);
		}
		buff.append(") values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);");
		obj[0] = AccessDataBaseUtil.getPKUUID();
		
		String curTime = FormatUtil.getCurentDateTime();
		obj[fields.length-4] = user.getUserId();
		obj[fields.length-3] = curTime;
		obj[fields.length-2] = user.getUserId();
		obj[fields.length-1] = curTime;
		
		AccessDataBaseUtil.executeSQLUpdate(buff.toString(), obj);
		return "\"保存成功\"";
	}

	@Override
	public Object update(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		String curTime = FormatUtil.getCurentDateTime();
		
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		StringBuffer buff = new StringBuffer();
		buff.append("update tma_dictionary set ");
		Object[] obj = new Object[fields.length];
		for(int j = 1; j < fields.length; j++) {
			obj[j - 1] = jsonObject.getString(fields[j]);
			buff.append(fields[j]).append(" = ?,");
		}
		buff.deleteCharAt(buff.length() - 1).append(" where tmad_id = ?");
		obj[fields.length-3] = user.getUserId();
		obj[fields.length-2] = curTime;
		obj[fields.length-1] = jsonObject.getString("tmad_id");
		
		AccessDataBaseUtil.executeSQLUpdate(buff.toString(), obj);
		return "\"修改成功\"";
	}

	@Override
	public Object delete(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("ids");
		String[] ids = id.split(",");
		sql = "delete from tma_dictionary where tmad_id = ?";
		
		AccessDataBaseUtil.deleteByIds(sql, ids);
		return "\"删除成功\"";
	}

	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		return request;
	}

	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object onCreate(Object jsonArray) {
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		return null;
	}

	@Override
	public Object onInit(Object jsonArray) {
		return null;
	}
	/**获取季统计报表表头
	 * @return
	 * @throws Exception
	 */
	public Object getConTitle(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String quarterly = jsonObject.getString("quarterly");
		String year = jsonObject.getString("year");
		String csql = "";
		List<Object[]> list = new ArrayList<Object[]>();
		if("".equals(year)){
			csql = "select a.tmad_id,a.tmad_name,b.tmgd_name from tma_dictionary a left join tm_general_dictionary b on a.tmad_kind = b.tmgd_id where a.tmad_kind not in('105-1','105-3','105-4','105-5') and a.tmad_status='0' and a.reserve1 ='1' order by a.tmad_kind desc, a.tmad_id";
		}else{
			csql = "select a.tmad_id,c.tmad_name,b.tmgd_name from tma_quarterly_usage a left join tm_general_dictionary b on a.tmad_kind = b.tmgd_id left join tma_dictionary c on a.tmad_id=c.tmad_id where a.tmad_kind not in('105-1','105-3','105-4','105-5') and a.tmaqu_time like'%"+year+"%' and a.tmaqu_quarterly = '"+quarterly+"' and a.org_id = '"+user.getCurOrgId()+"' order by a.tmad_kind desc, a.tmad_id";
		}
		list = AccessDataBaseUtil.query(csql, null);
		if(list.size() == 0){
			csql = "select a.tmad_id,a.tmad_name,b.tmgd_name from tma_dictionary a left join tm_general_dictionary b on a.tmad_kind = b.tmgd_id where a.tmad_kind not in('105-1','105-3','105-4','105-5') and a.tmad_status='0' and a.reserve1 ='1' order by a.tmad_kind desc, a.tmad_id";
			list = AccessDataBaseUtil.query(csql, null);
		}
		JSONArray arr = new JSONArray ();
		JSONArray children = new JSONArray();;
		JSONObject obj = new JSONObject();
		JSONObject child;
		Object[] o;
		for(int i = 0; i < list.size(); i++){
			o = list.get(i);
			if(i > 0){
				if(o[2] == null || "".equals(o[2])){
					obj.put("children", children);
					arr.add(obj);
					obj = new JSONObject();
					children = new JSONArray();
					obj.put("name", o[1]);
				}
				else{
					if(!obj.getString("name").equals(o[2])){
						obj.put("children", children);
						arr.add(obj);
						obj = new JSONObject();
						children = new JSONArray();
						obj.put("name", o[2]);
					}
					child = new JSONObject();
					child.put("name", o[1]);
					children.add(child);
				}
			}else{
				obj.put("name", o[2]);
				child = new JSONObject();
				child.put("name", o[1]);
				children.add(child);
			}
			
		}
		obj.put("children", children);
		arr.add(obj);
		return arr.toString();
	}
	private boolean delReport(){
		StringBuffer buff = new StringBuffer();
//		buff("selsedt")
		return false;
	}
}


